import region from "@src/models/region";
import moment from "moment";
import Constant from "@src/util/constant";
import literature from "@src/models/literature";
import article from "@src/models/article";
import File from "@src/models/file";
import {Op} from "sequelize";
import Dict from "@src/models/dict";

// 是否存在该区域,id为字典id
const isRegionDictId = async (category_id: string) => {
  return region.findOne({
    where: {
      category_id,
    },
  });
};

// 通过区域本身id查
const isRegionId = async (id: string) => {
  return region.findOne({
    where: {
      id,
    },
  });
};

// 更新区域
const update = async (content: string, images: string[], videos: string[], id: string) => {
  await region.update({
    content,
    images,
    videos,
    updated_at: moment().format("X"),
  }, {
    where: {
      id,
    },
  });
  return Constant.DEFAULT_SUCCESS;
};

// 关联文献
const relationLiterature = async (id: string, literature_id: string) => {
  literature.update({
    region_id: id,
    updated_at: moment().format("X"),
  }, {
    where: {
      id: literature_id,
    },
  });
  return Constant.DEFAULT_SUCCESS;
};

// 关联文章
const relationArticle = async (id: string, article_id: string) => {
  article.update({
    region_id: id,
    updated_at: moment().format("X"),
  }, {
    where: {
      id: article_id,
    },
  });
  return Constant.DEFAULT_SUCCESS;
};

// 取消文献关联
const cancelRelationLiterature = async (id: string) => {
  literature.update({
    region_id: null,
    updated_at: moment().format("X"),
  }, {
    where: {
      id,
    },
  });
  return Constant.DEFAULT_SUCCESS;
};

// 取消文章关联
const cancelRelationArticle = async (id: string) => {
  article.update({
    region_id: null,
    updated_at: moment().format("X"),
  }, {
    where: {
      id,
    },
  });
  return Constant.DEFAULT_SUCCESS;
};

// 文件遍历获取
const fileInfo = async (id: string[]) => {
  if (id.length === 0) {
    return [];
  }
  return await File.findAll({
    attributes: ["id", "size", "type", "path"],
    where: {
      id: {
        [Op.or]: id,
      },
    },
  });
};

// 区域详情
const detail = async (id: string) => {
  const regionData: any = await region.findOne({
    where: {
      category_id: id,
    },
    attributes: ["id", "name", "images", "videos", "visit_num", "content", "category_id"],
  });
  const images = await fileInfo(regionData.images);
  const videos = await fileInfo(regionData.videos);
  return {
    ...Constant.DEFAULT_SUCCESS,
    data: {
      id: regionData.id,
      images,
      videos,
      name: regionData.name,
      content: regionData.content,
      visit_num: regionData.visit_num,
    },
  };
};

// 文章关联查询
const relationArticleList = async (offset: number, limit: number, filters: { name: string, region_id: null }, id: string) => {
  let whereObj: any = {
    region_id: id,
  };
  for (const v in filters) {
    if (v === "name" && filters[v]) {
      whereObj[v] = {
        [Op.substring]: filters[v],
      };
    }
    if (v === "region_id" && filters[v] == 0) {
      whereObj[v] = null;
    }
  }
  const {count, rows} = await article.findAndCountAll({
    attributes: ["id", "name", "username", "visit_num", "category_id", "region_id"],
    where: whereObj,
    offset,
    limit,
    include: [
      {
        attributes: ["id", "size", "type", "path"],
        model: File,
        // 指定别名
        as: "cover",
      },
      {
        attributes: ["type_id", "name"],
        model: Dict,
        as: "dict",
      },
    ],
  });
  return {count, rows};
};

// 关联文献
const relationLiteratureList = async (offset: number, limit: number, filters: { name: string, region_id: null }, id: string) => {
  let whereObj: any = {
    region_id: id,
  };
  for (const v in filters) {
    if (v === "name" && filters[v]) {
      whereObj[v] = {
        [Op.substring]: filters[v],
      };
    }
    if (v === "region_id" && filters[v] == 0) {
      whereObj[v] = null;
    }
  }
  const {count, rows} = await literature.findAndCountAll({
    attributes: ["id", "name", "author", "category_id", "visit_num", "introduce"],
    where: whereObj,
    offset,
    limit,
    include: [
      {
        attributes: ["id", "size", "type", "path"],
        model: File,
        // 多个关联外键同时查询
        all: true,
      },
      {
        attributes: ["type_id", "name"],
        model: Dict,
        as: "dict",
      },
    ],
  });
  return {count, rows};
};

// 区域排名
const ranking = async () => {
  const data = await region.findAndCountAll({
    attributes: ["id", "name", "visit_num"],
    offset: 0,
    limit: 7,
    order: [
      ['visit_num', 'DESC'],
    ],
  });
  return {
    data,
    ...Constant.DEFAULT_SUCCESS,
  };
};

export default {
  isRegionId,
  update,
  relationLiterature,
  relationArticle,
  cancelRelationLiterature,
  cancelRelationArticle,
  detail,
  relationArticleList,
  relationLiteratureList,
  isRegionDictId,
  ranking,
};